<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Session;
use Crypt;
class LoginController extends Controller
{
	//注册页面
	public function reg()
	{
		return view('home.login.reg');
	}

    public function doReg(Request $request)
    {
        if($request['password']!=$request['repassword']){
            return back()->with(['info' => '确认密码与原密码不一致']);
        }
        
        $data = $request -> except('_token','repassword','code');
        //处理密码
        $data['password'] = Crypt::encrypt($data['password']);
        // $p = Crypt::decrypt($data['password']);
        // dd($p);
        //处理token字段
        $data['remember_token'] = str_random(50);

        // dd($data);
        $res = DB::table('users')
            ->insert($data);
        // dd($data);
        return redirect('/login') -> with(['info' => '注册成功']);
    }
    public function ajaxE(Request $request){
        // dd($request->email);
        $data = DB::table('users')
            ->where('email',$request->email)
            ->get();
        if($data){
            return 2;
        }else{
            return 1;
        }       
    }
    //login
    public function login()
    {
    	return view('home.login.login');
    }

//doLogin
    public function dologin(Request $request){
        $data = $request -> except('_token');
        // dd($data);
        // 检测验证码是否正确
        $code = Session::get('milkcaptcha');
        if ($code != $data['captcha']) {
            return back() -> with(['info' => '验证码有误！']);
        }
        $res = DB::table('users') -> where('email',$data['email']) -> first();
        if(!$res){
            return back() -> with(['info' => '你输入的邮箱不存在']);
        }

        $password = $res -> password;
        // 解密
        $password = Crypt::decrypt($password);

        // 判断
        if($data['password'] != $password){
            return back() -> with(['info' => '你输入的邮箱或者密码错误']);
        }
        session(['home' => $res]);
        // dd($res);
        return redirect('/') -> with(['info' => '登录成功']);
    }
    public function logout()
    {
        Session::forget('home');
        return redirect('/') -> with(['info' => '退出成功']);
    }
}
